<script setup lang="ts">
import { computed, ref, onMounted, onUnmounted } from 'vue'
import { useYklibLoginStore } from 'yklib'
import CollapsibleSection from '../components/CollapsibleSection.vue'
import InstallDockerImage from './InstallDockerImage.vue'
import DockerRun from './DockerRun.vue'
import QuickDeploy from './QuickDeploy.vue'

const store = useYklibLoginStore()

const showSettings = ref(false)
const serverConfig = ref({
  ip: '',
  port: 22,
  username: '',
  password: '',
  authType: 'password',
  privateKey: ''
})

const testStatus = ref('') // 测试连接状态

const dockerInstalled = ref('') // Docker安装状态

const saveSettings = () => {
  showSettings.value = false
  store.saveProjectSettings({ serverConfig: serverConfig.value })
}



const testConnection = async () => {
  testStatus.value = '测试连接中...'
  // @ts-ignore
  window.pywebview.api.testConnection(serverConfig.value).then((response: { 'suc': boolean, 'msg': string }) => {
    console.log('测试连接结果:', response)
    if (response.suc) {
      testStatus.value = '连接成功 ✓'
    } else {
      testStatus.value = `SSH模块加载失败: ${response}`
    }
  });
}

const loadSettings = async () => {
  const settings = await store.loadProjectSettings()
  if (settings?.serverConfig) {
    serverConfig.value = { ...serverConfig.value, ...settings.serverConfig }
    console.log('加载服务器配置:', serverConfig.value)
  }
  if (settings?.docker) {
    dockerInfo.value = {
      installed: settings.docker.installed || false,
      mirrors: settings.docker.mirrors || []
    }
    if (settings.docker.installed) {
      dockerInstalled.value = 'Docker已安装 ✓'
    } else {
      dockerInstalled.value = 'Docker未安装或状态未知，请先安装Docker!'
    }
    console.log('加载Docker配置:', dockerInfo.value)
  }
}

onMounted(() => {
  loadSettings() // 页面加载时加载设置，该组件为App.vue的子组件，跳转到这里时，pywebview必然已经加载完成，所以可以直接调用
})

const installDocker = async () => {
  if (!store.isPywebview) {
    alert('请在pywebview环境下运行')
    return
  }
  // @ts-ignore
  window.pywebview.api.installDocker(serverConfig.value).then((response: { 'suc': boolean, 'msg': string }) => {
    console.log('安装Docker结果:', response)
    if (response.suc) {
      dockerInstalled.value = `安装成功: ${response.msg}`
      dockerInfo.value = { ...dockerInfo.value, installed: true }
      // 自动打开镜像设置窗口
      showMirrorSettings.value = true
    } else {
      dockerInstalled.value = `安装失败: ${response.msg}`
      dockerInfo.value = { ...dockerInfo.value, installed: false }
    }
  });
}

const showMirrorSettings = ref(false)
const mirrorOptions = ref([
  'https://docker.xuanyuan.me',
  'https://docker.1ms.run'
])
const dockerInfo = ref<{
  installed: boolean
  mirrors: string[] | string
}>({
  installed: false,
  mirrors: [] as string[]
})


const setDockerMirror = async () => {
  showMirrorSettings.value = false
  // 处理手动输入的镜像源（按换行分割）
  if (typeof dockerInfo.value.mirrors === 'string') {
    dockerInfo.value.mirrors = dockerInfo.value.mirrors
      .split('\n')
      .map(m => m.trim())
      .filter(m => m.length > 0)
  }

  if (dockerInfo.value.mirrors.length === 0) return

  store.saveProjectSettings({ docker: dockerInfo.value })

  // @ts-ignore
  window.pywebview.api.saveProjectSettings({
    serverConfig: serverConfig.value,
    docker: dockerInfo.value,
  }).then((response: { 'suc': boolean, 'msg': string }) => {

  }).catch(() => {

  });
}
const mirrorText = computed({
  get: () => {
    if (Array.isArray(dockerInfo.value.mirrors)) {
      return dockerInfo.value.mirrors.join('\n')
    }
    return dockerInfo.value.mirrors
  },
  set: (value) => {
    dockerInfo.value.mirrors = value
  }
})
const dockerSectionExpanded = ref(true)
const installImagesExpanded = ref(true)
const dockerRunExpanded = ref(true)
const quickDeployExpanded = ref(true)
</script>

<template>
  <div class="container bg-blue-100 p-4">
    <CollapsibleSection title="Docker安装与配置" v-model:expanded="dockerSectionExpanded" class="mb-4"> <!-- 添加下边距 -->

      <div class="space-y-3">
        <div class="flex space-x-2">
          <button @click="showSettings = true"
            class="bg-gray-500 text-white py-2 px-7 rounded-lg shadow-md hover:bg-gray-600 h-[42px]">
            服务器设置
          </button>
          <button @click="installDocker"
            class="bg-purple-500 text-white py-2 px-7 rounded-lg shadow-md hover:bg-purple-600 h-[42px]">
            安装Docker
          </button>
          <button @click="showMirrorSettings = true" :disabled="!dockerInfo.installed"
            class="bg-blue-500 text-white py-2 px-7 rounded-lg shadow-md hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed h-[42px]">
            设置Docker加速服务器
          </button>
        </div>
        <div class="space-y-3 bg-gray-50 p-3 rounded-lg">
          <div class="flex items-center space-x-2">
            <span class="text-sm font-medium text-gray-600">服务器信息：</span>
            <span v-if="serverConfig.ip" class="text-sm bg-blue-100 px-2 py-1 rounded-md">
              {{ serverConfig.ip }}:{{ serverConfig.port }} ({{ serverConfig.username }})
            </span>
            <span v-else class="text-sm text-gray-500">未配置</span>
          </div>

          <div class="flex items-center space-x-2">
            <span class="text-sm font-medium text-gray-600">Docker状态：</span>
            <span :class="{
              'text-green-600': dockerInstalled.includes('成功') || dockerInstalled.includes('已安装'),
              'text-red-600': dockerInstalled.includes('失败') || dockerInstalled.includes('未安装')
            }" class="text-sm">
              {{ dockerInstalled || '未知' }}
            </span>
          </div>

          <div class="flex items-center space-x-2">
            <span class="text-sm font-medium text-gray-600">镜像源：</span>
            <template v-if="dockerInfo.mirrors.length > 0">
              <span v-for="(mirror, index) in dockerInfo.mirrors" :key="index"
                class="text-sm bg-gray-200 px-2 py-1 rounded-md">
                {{ mirror }}
              </span>
            </template>
            <span v-else class="text-sm text-gray-500">未配置</span>
          </div>
        </div>

      </div>
    </CollapsibleSection>

    <CollapsibleSection title="安装Docker镜像" v-model:expanded="installImagesExpanded"> <!-- 添加下边距 -->
      <InstallDockerImage></InstallDockerImage>
    </CollapsibleSection>

    <CollapsibleSection title="快速部署" v-model:expanded="quickDeployExpanded"> <!-- 添加下边距 -->
      <QuickDeploy></QuickDeploy>
    </CollapsibleSection>

    <CollapsibleSection title="Docker运行" v-model:expanded="dockerRunExpanded"> <!-- 添加下边距 -->
      <DockerRun></DockerRun>
    </CollapsibleSection>
    <!-- 镜像源设置弹窗 -->
    <div v-if="showMirrorSettings" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white p-6 rounded-lg w-96 shadow-xl">
        <h2 class="text-xl font-bold mb-4 text-gray-800">设置Docker镜像源</h2>

        <div class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">选择镜像源</label>
            <select v-model="dockerInfo.mirrors" multiple
              class="mt-1 block w-full border border-gray-300 rounded-md p-2 h-32">
              <option v-for="option in mirrorOptions" :value="option">{{ option }}</option>
            </select>

            <textarea v-model="mirrorText" rows="4" class="mt-1 block w-full border border-gray-300 rounded-md p-2"
              placeholder="输入镜像源地址，每行一个地址，如:&#10;https://mirror1&#10;https://mirror2">
        </textarea>
          </div>
        </div>

        <div class="mt-6 flex justify-end space-x-3">
          <button @click="showMirrorSettings = false"
            class="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-50">
            取消
          </button>
          <button @click="setDockerMirror" class="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600">
            保存
          </button>
        </div>
      </div>
    </div>



    <!-- 设置弹窗 -->
    <div v-if="showSettings" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white p-6 rounded-lg w-96 shadow-xl">
        <h2 class="text-xl font-bold mb-4 text-gray-800">服务器连接设置</h2>

        <div class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">服务器IP</label>
            <input v-model="serverConfig.ip" type="text"
              class="mt-1 block w-full border border-gray-300 rounded-md p-2 focus:ring-blue-500 focus:border-blue-500">
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">端口</label>
            <input v-model.number="serverConfig.port" type="number"
              class="mt-1 block w-full border border-gray-300 rounded-md p-2 focus:ring-blue-500 focus:border-blue-500">
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
            <input v-model="serverConfig.username" type="text"
              class="mt-1 block w-full border border-gray-300 rounded-md p-2 focus:ring-blue-500 focus:border-blue-500">
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">认证方式</label>
            <select v-model="serverConfig.authType"
              class="mt-1 block w-full border border-gray-300 rounded-md p-2 focus:ring-blue-500 focus:border-blue-500">
              <option value="password">密码认证</option>
              <option value="key">密钥认证</option>
            </select>
          </div>

          <div v-if="serverConfig.authType === 'password'">
            <label class="block text-sm font-medium text-gray-700 mb-1">密码</label>
            <input v-model="serverConfig.password" type="password"
              class="mt-1 block w-full border border-gray-300 rounded-md p-2 focus:ring-blue-500 focus:border-blue-500">
          </div>

          <div v-if="serverConfig.authType === 'key'">
            <label class="block text-sm font-medium text-gray-700 mb-1">私钥</label>
            <textarea v-model="serverConfig.privateKey" rows="4"
              class="mt-1 block w-full border border-gray-300 rounded-md p-2 focus:ring-blue-500 focus:border-blue-500"></textarea>
          </div>
        </div>

        <div class="mt-6 text-sm text-gray-600 min-h-6">
          <div :class="{ 'text-green-600': testStatus.includes('成功'), 'text-red-600': testStatus.includes('失败') }">
            {{ testStatus }}
          </div>
        </div>

        <div class="mt-6 flex justify-end space-x-3">
          <button @click="testConnection"
            class="px-4 py-2 bg-green-500 text-white rounded-md hover:bg-green-600 transition-colors">
            测试连接
          </button>
          <button @click="showSettings = false"
            class="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-50 transition-colors">
            取消
          </button>
          <button @click="saveSettings"
            class="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition-colors">
            保存
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="postcss" scoped>
.container {
  width: 100%;
  height: 100%;
}
</style>
